<template>
  <t-dialog
    :visible="visible"
    @update:visible="$emit('update:visible', $event)"
    :header="title"
    :width="600"
    :footer="false"
    @close="handleClose"
  >
    <div class="user-role-container">
      <!-- 用户信息展示 -->
      <div v-if="!isBatch" class="user-info-section">
        <div class="user-card">
          <t-avatar :size="40" :image="currentUser?.avatar">
            {{ (currentUser?.nickname || currentUser?.username || 'U').charAt(0).toUpperCase() }}
          </t-avatar>
          <div class="user-details">
            <div class="user-name">{{ currentUser?.nickname || currentUser?.username }}</div>
            <div class="user-meta">{{ currentUser?.email }}</div>
          </div>
        </div>
      </div>
      
      <!-- 批量操作用户列表 -->
      <div v-else class="batch-users-section">
        <div class="batch-header">
          <h4>选中用户 ({{ selectedUsers.length }}个)</h4>
        </div>
        <div class="batch-users-list">
          <div
            v-for="user in selectedUsers"
            :key="user.id"
            class="batch-user-item"
          >
            <t-avatar :size="24" :image="user.avatar">
              {{ (user.nickname || user.username || 'U').charAt(0).toUpperCase() }}
            </t-avatar>
            <span class="batch-user-name">{{ user.nickname || user.username }}</span>
          </div>
        </div>
      </div>
      
      <!-- 当前角色 -->
      <div v-if="!isBatch && currentUserRoles.length > 0" class="current-roles-section">
        <h4 class="section-title">当前角色</h4>
        <div class="current-roles">
          <t-tag
            v-for="role in currentUserRoles"
            :key="role.id"
            theme="primary"
            variant="light"
            class="role-tag"
          >
            {{ role.name }}
          </t-tag>
        </div>
      </div>
      
      <!-- 角色选择 -->
      <div class="role-selection-section">
        <h4 class="section-title">{{ isBatch ? '分配角色' : '选择角色' }}</h4>
        <div class="role-options">
          <div
            v-for="role in availableRoles"
            :key="role.id"
            class="role-option"
            :class="{ 'selected': selectedRoleIds.includes(role.id) }"
            @click="toggleRole(role.id)"
          >
            <div class="role-option-header">
              <t-checkbox
                :checked="selectedRoleIds.includes(role.id)"
                @change="(checked) => handleRoleChange(role.id, checked)"
              />
              <div class="role-info">
                <div class="role-name">{{ role.name }}</div>
                <div class="role-description">{{ role.description }}</div>
              </div>
            </div>
            
            <!-- 角色权限预览 -->
            <div v-if="role.permissions && role.permissions.length > 0" class="role-permissions">
              <div class="permissions-label">包含权限:</div>
              <div class="permissions-tags">
                <t-tag
                  v-for="permission in role.permissions.slice(0, 5)"
                  :key="permission.id"
                  size="small"
                  variant="outline"
                  class="permission-tag"
                >
                  {{ permission.name }}
                </t-tag>
                <t-tag
                  v-if="role.permissions.length > 5"
                  size="small"
                  variant="outline"
                  class="permission-tag more-tag"
                >
                  +{{ role.permissions.length - 5 }}
                </t-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 操作说明 -->
      <div class="operation-tips">
        <t-alert theme="info" :close="false">
          <template #icon>
            <component :is="'InfoCircleIcon'" />
          </template>
          {{ isBatch ? '批量分配角色将会覆盖所选用户的现有角色' : '重新分配角色将会覆盖用户的现有角色' }}
        </t-alert>
      </div>
      
      <!-- 操作按钮 -->
      <div class="role-footer">
        <t-space>
          <t-button @click="handleClose">取消</t-button>
          <t-button 
            theme="primary" 
            :loading="loading"
            :disabled="selectedRoleIds.length === 0"
            @click="handleSubmit"
          >
            确认分配
          </t-button>
        </t-space>
      </div>
    </div>
  </t-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'

// 定义 props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  currentUser: {
    type: Object,
    default: null
  },
  selectedUsers: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  }
})

// 定义 emits
const emit = defineEmits(['update:visible', 'submit', 'close'])

// 选中的角色ID
const selectedRoleIds = ref([])

// 计算属性
const isBatch = computed(() => props.selectedUsers.length > 1)
const title = computed(() => isBatch.value ? '批量分配角色' : '分配用户角色')

// 当前用户的角色
const currentUserRoles = computed(() => {
  if (isBatch.value || !props.currentUser) return []
  return props.currentUser.roles || []
})

// 可用角色列表
const availableRoles = ref([
  {
    id: '1',
    name: '超级管理员',
    description: '拥有系统所有权限，可以进行任何操作',
    permissions: [
      { id: '1', name: '用户管理' },
      { id: '2', name: '角色管理' },
      { id: '3', name: '权限管理' },
      { id: '4', name: '系统设置' },
      { id: '5', name: '数据统计' },
      { id: '6', name: '日志查看' }
    ]
  },
  {
    id: '2',
    name: '管理员',
    description: '拥有大部分管理权限，可以管理用户和基础数据',
    permissions: [
      { id: '1', name: '用户管理' },
      { id: '2', name: '角色管理' },
      { id: '7', name: '商品管理' },
      { id: '8', name: '订单管理' },
      { id: '9', name: '客户管理' }
    ]
  },
  {
    id: '3',
    name: '运营专员',
    description: '负责日常运营工作，可以处理订单和客户相关事务',
    permissions: [
      { id: '7', name: '商品管理' },
      { id: '8', name: '订单管理' },
      { id: '9', name: '客户管理' },
      { id: '10', name: '库存管理' }
    ]
  },
  {
    id: '4',
    name: '财务专员',
    description: '负责财务相关工作，可以查看和管理财务数据',
    permissions: [
      { id: '11', name: '财务管理' },
      { id: '12', name: '报表查看' },
      { id: '13', name: '账目核对' }
    ]
  },
  {
    id: '5',
    name: '普通用户',
    description: '基础用户权限，只能查看基本信息',
    permissions: [
      { id: '14', name: '基础查看' },
      { id: '15', name: '个人信息' }
    ]
  }
])

// 切换角色选择
const toggleRole = (roleId) => {
  const index = selectedRoleIds.value.indexOf(roleId)
  if (index > -1) {
    selectedRoleIds.value.splice(index, 1)
  } else {
    selectedRoleIds.value.push(roleId)
  }
}

// 处理角色变化
const handleRoleChange = (roleId, checked) => {
  if (checked) {
    if (!selectedRoleIds.value.includes(roleId)) {
      selectedRoleIds.value.push(roleId)
    }
  } else {
    const index = selectedRoleIds.value.indexOf(roleId)
    if (index > -1) {
      selectedRoleIds.value.splice(index, 1)
    }
  }
}

// 处理提交
const handleSubmit = () => {
  if (selectedRoleIds.value.length === 0) {
    MessagePlugin.warning('请至少选择一个角色')
    return
  }
  
  const submitData = {
    roleIds: selectedRoleIds.value,
    userIds: isBatch.value 
      ? props.selectedUsers.map(user => user.id)
      : [props.currentUser.id]
  }
  
  emit('submit', submitData)
}

// 处理关闭
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
  resetForm()
}

// 重置表单
const resetForm = () => {
  selectedRoleIds.value = []
}

// 初始化选中角色
const initSelectedRoles = () => {
  if (!isBatch.value && props.currentUser && props.currentUser.roles) {
    selectedRoleIds.value = props.currentUser.roles.map(role => role.id)
  } else {
    selectedRoleIds.value = []
  }
}

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initSelectedRoles()
  } else {
    resetForm()
  }
})

// 监听当前用户变化
watch(() => props.currentUser, () => {
  if (props.visible) {
    initSelectedRoles()
  }
}, { deep: true })
</script>

<style scoped>
.user-role-container {
  padding: 24px;
}

/* 用户信息部分 */
.user-info-section {
  margin-bottom: 24px;
}

.user-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: var(--td-bg-color-container);
  border-radius: 8px;
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: 500;
  color: var(--td-text-color-primary);
  margin-bottom: 4px;
}

.user-meta {
  font-size: 14px;
  color: var(--td-text-color-secondary);
}

/* 批量用户部分 */
.batch-users-section {
  margin-bottom: 24px;
}

.batch-header h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 500;
  color: var(--td-text-color-primary);
}

.batch-users-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  max-height: 120px;
  overflow-y: auto;
  padding: 12px;
  background: var(--td-bg-color-container);
  border-radius: 8px;
}

.batch-user-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 8px;
  background: white;
  border-radius: 4px;
  font-size: 12px;
}

.batch-user-name {
  color: var(--td-text-color-primary);
}

/* 当前角色部分 */
.current-roles-section {
  margin-bottom: 24px;
}

.section-title {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 500;
  color: var(--td-text-color-primary);
}

.current-roles {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.role-tag {
  border-radius: 6px;
}

/* 角色选择部分 */
.role-selection-section {
  margin-bottom: 24px;
}

.role-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.role-option {
  padding: 16px;
  border: 1px solid var(--td-border-level-1-color);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.role-option:hover {
  border-color: var(--td-brand-color);
  background: var(--td-brand-color-light);
}

.role-option.selected {
  border-color: var(--td-brand-color);
  background: var(--td-brand-color-focus);
}

.role-option-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 12px;
}

.role-info {
  flex: 1;
}

.role-name {
  font-size: 16px;
  font-weight: 500;
  color: var(--td-text-color-primary);
  margin-bottom: 4px;
}

.role-description {
  font-size: 14px;
  color: var(--td-text-color-secondary);
  line-height: 1.4;
}

.role-permissions {
  margin-left: 36px;
}

.permissions-label {
  font-size: 12px;
  color: var(--td-text-color-secondary);
  margin-bottom: 8px;
}

.permissions-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.permission-tag {
  border-radius: 4px;
  font-size: 12px;
}

.more-tag {
  color: var(--td-brand-color);
  border-color: var(--td-brand-color);
}

/* 操作说明 */
.operation-tips {
  margin-bottom: 24px;
}

/* 底部操作 */
.role-footer {
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-role-container {
    padding: 16px;
  }
  
  .role-option-header {
    flex-direction: column;
    gap: 8px;
  }
  
  .role-permissions {
    margin-left: 0;
    margin-top: 8px;
  }
  
  .batch-users-list {
    max-height: 80px;
  }
}
</style> 